<template>
  <a-layout class="statistics-dashboard">
    <!-- 主要内容区 -->
    <a-layout-content class="content">
      <div class="page-title">借阅数据统计分析</div>
      <!-- 加载状态 -->
      <a-spin :spinning="loading" tip="数据加载中...">
        <!-- 数据概览卡片 -->
        <a-row :gutter="16" class="stats-cards">
          <a-col :xs="24" :sm="12" :lg="6" class="stat-card">
            <a-card hoverable class="card">
              <div class="card-title">总借阅次数</div>
              <div class="card-value">{{ totalBorrows }}</div>
              <div class="card-trend">
                <span class="trend-up">↑ 12.5%</span>
                <span class="trend-desc">较上月</span>
              </div>
            </a-card>
          </a-col>
          <a-col :xs="24" :sm="12" :lg="6" class="stat-card">
            <a-card hoverable class="card">
              <div class="card-title">热门图书数</div>
              <div class="card-value">{{ hotBooksData.length }}</div>
              <div class="card-trend">
                <span class="trend-up">↑ 8.2%</span>
                <span class="trend-desc">较上月</span>
              </div>
            </a-card>
          </a-col>
          <a-col :xs="24" :sm="12" :lg="6" class="stat-card">
            <a-card hoverable class="card">
              <div class="card-title">活跃用户数</div>
              <div class="card-value">{{ activeUsersData.length }}</div>
              <div class="card-trend">
                <span class="trend-down">↓ 3.1%</span>
                <span class="trend-desc">较上月</span>
              </div>
            </a-card>
          </a-col>
          <a-col :xs="24" :sm="12" :lg="6" class="stat-card">
            <a-card hoverable class="card">
              <div class="card-title">平均借阅次数</div>
              <div class="card-value">{{ avgBorrowsPerUser.toFixed(1) }}</div>
              <div class="card-trend">
                <span class="trend-up">↑ 5.7%</span>
                <span class="trend-desc">较上月</span>
              </div>
            </a-card>
          </a-col>
        </a-row>

        <!-- 图表区域 -->
        <a-row :gutter="16" class="charts-container">
          <!-- 图书借阅排行榜 -->
          <a-col :xs="24" :lg="12" class="chart-wrapper">
            <a-card class="chart-card">
              <div slot="title" class="chart-title">
                <span>图书借阅排行榜</span>
                <a-select
                  v-model:value="bookTimeRange"
                  style="width: 120px"
                  @change="handleBookTimeRangeChange"
                >
                  <a-select-option value="week">近一周</a-select-option>
                  <a-select-option value="month">近一月</a-select-option>
                  <a-select-option value="quarter">近三月</a-select-option>
                  <a-select-option value="year">近一年</a-select-option>
                </a-select>
              </div>
              <div class="chart-content">
                <div ref="bookChartRef" class="chart" />
              </div>
            </a-card>
          </a-col>

          <!-- 用户借阅排行榜 -->
          <a-col :xs="24" :lg="12" class="chart-wrapper">
            <a-card class="chart-card">
              <div slot="title" class="chart-title">
                <span>用户借阅排行榜</span>
                <a-select
                  v-model:value="userTimeRange"
                  style="width: 120px"
                  @change="handleUserTimeRangeChange"
                >
                  <a-select-option value="week">近一周</a-select-option>
                  <a-select-option value="month">近一月</a-select-option>
                  <a-select-option value="quarter">近三月</a-select-option>
                  <a-select-option value="year">近一年</a-select-option>
                </a-select>
              </div>
              <div class="chart-content">
                <div ref="userChartRef" class="chart" />
              </div>
            </a-card>
          </a-col>
        </a-row>

        <!-- 详细数据表格 -->
        <a-row :gutter="16" class="tables-container">
          <a-col :xs="24" :lg="12" class="table-wrapper">
            <a-card class="data-table">
              <div slot="title">热门图书详情</div>
              <a-table
                :columns="bookColumns"
                :data-source="hotBooksData"
                :pagination="false"
                row-key="id"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'book_url'">
                    <a-avatar :src="record.book_url" shape="square" size="small" />
                  </template>
                  <template v-if="column.dataIndex === 'borrowCount'">
                    <span class="count-badge">{{ record.borrowCount }}</span>
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-col>

          <a-col :xs="24" :lg="12" class="table-wrapper">
            <a-card class="data-table">
              <div slot="title">活跃用户详情</div>
              <a-table
                :columns="userColumns"
                :data-source="activeUsersData"
                :pagination="false"
                row-key="book_id"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'userAvatar'">
                    <a-avatar :src="record.userAvatar" />
                  </template>
                  <template v-if="column.dataIndex === 'totalRecord'">
                    <span class="count-badge">{{ record.totalRecord }}</span>
                  </template>
                  <template v-if="column.dataIndex === 'userRole'">
                    <a-tag class="count-badge">{{ record.userRole }}</a-tag>
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-col>
        </a-row>
      </a-spin>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="ts">
import { getHotBookListUsingGet } from '@/api/bookController' // 导入图书API
import { getHotUserListUsingGet } from '@/api/userController' // 导入用户API
import * as echarts from 'echarts'
import { onMounted, ref } from 'vue'

// 状态管理
const loading = ref(true)
const totalBorrows = ref(0)
const avgBorrowsPerUser = ref(0)

// 时间范围选择
const bookTimeRange = ref('month')
const userTimeRange = ref('month')

// 数据存储
const hotBooksData = ref([])
const activeUsersData = ref([])

// 表格列定义
const bookColumns = [
  { title: '封面', dataIndex: 'book_url', width: 80 },
  { title: '书名', dataIndex: 'book_name', ellipsis: true },
  { title: '作者', dataIndex: 'book_author' },
  { title: '借阅次数', dataIndex: 'record_count', align: 'right' },
]

const userColumns = [
  { title: '头像', dataIndex: 'userAvatar', width: 60 },
  { title: '用户名', dataIndex: 'userName' },
  { title: '身份', dataIndex: 'userRole' },
  { title: '借阅次数', dataIndex: 'totalRecord', align: 'right' },
]

// 图表引用
const bookChartRef = ref(null)
const userChartRef = ref(null)
let bookChart = null
let userChart = null

// 从API获取热门图书数据
const fetchHotBooks = async (timeRange = 'month') => {
  try {
    const res = await getHotBookListUsingGet({ timeRange })
    console.log('热门图书：', res)
    if (res.data.code === 0 && res.data) {
      hotBooksData.value = res.data.data
      // 计算总借阅次数
      calculateTotalBorrows()
      // 更新图表
      updateBookChart()
    } else {
      console.error('获取热门图书数据失败:', res.message)
    }
  } catch (error) {
    console.error('获取热门图书数据出错:', error)
  }
}

// 从API获取活跃用户数据
const fetchHotUsers = async (timeRange = 'month') => {
  try {
    const res = await getHotUserListUsingGet({ timeRange })
    if (res.data.code === 0 && res.data) {
      activeUsersData.value = res.data.data
      // 计算平均借阅次数
      calculateAvgBorrows()
      // 更新图表
      updateUserChart()
    } else {
      console.error('获取活跃用户数据失败:', res.message)
    }
  } catch (error) {
    console.error('获取活跃用户数据出错:', error)
  } finally {
    loading.value = false
  }
}

// 计算总借阅次数
const calculateTotalBorrows = () => {
  // 使用API返回的record_count字段
  totalBorrows.value = hotBooksData.value.reduce((sum, book) => sum + (book.record_count || 0), 0)
}

// 计算平均借阅次数
const calculateAvgBorrows = () => {
  const total = activeUsersData.value.reduce((sum, user) => sum + (user.totalRecord || 0), 0)
  avgBorrowsPerUser.value =
    activeUsersData.value.length > 0 ? total / activeUsersData.value.length : 0
}

// 初始化图书借阅排行榜图表
const initBookChart = () => {
  if (bookChartRef.value) {
    bookChart = echarts.init(bookChartRef.value)
    updateBookChart()
  }
}

const updateBookChart = () => {
  if (!bookChart) return

  const bookNames = hotBooksData.value.map((book) => book.book_name || '未知图书')
  const borrowCounts = hotBooksData.value.map((book) => book.record_count || 0)

  const option = {
    tooltip: {
      /* 保持原有配置 */
    },
    // 关键：增加左侧边距，为长书名预留空间
    grid: {
      left: '5%', // 从15%调整为20%，进一步扩大左侧空间
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      /* 保持原有配置 */
    },
    yAxis: {
      type: 'category',
      data: bookNames,
      axisLine: { show: true },
      axisTick: { show: false },
      inverse: true,
      animationDuration: 300,
      animationDurationUpdate: 300,
      // 优化文字显示：自动换行或省略
      axisLabel: {
        width: 180, // 限制文字宽度
        overflow: 'truncate', // 换行（或用'truncate'省略）
        lineHeight: 20, // 行高，保证换行后间距
        formatter: (value) => {
          return value
        },
      },
    },
    series: [
      {
        name: '借阅次数',
        type: 'bar',
        data: borrowCounts,
        barWidth: 15, // 减小柱宽，提升紧凑感
        itemStyle: {
          /* 保持原有配置 */
        },
        emphasis: {
          /* 保持原有配置 */
        },
        animationDuration: 800,
      },
    ],
  }

  bookChart.setOption(option)
}
// 初始化用户借阅排行榜图表
const initUserChart = () => {
  if (userChartRef.value) {
    userChart = echarts.init(userChartRef.value)
    updateUserChart()
  }
}

// 更新用户图表数据
const updateUserChart = () => {
  if (!userChart) return

  // 处理数据
  const userNames = activeUsersData.value.map((user) => user.userName || '未知用户')
  const borrowCounts = activeUsersData.value.map((user) => user.totalRecord || 0)

  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      padding: [10, 15],
      borderColor: '#eee',
      borderWidth: 1,
      textStyle: {
        color: '#333',
      },
      formatter: '{a} <br/>{b}: {c}次 ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 10,
      textStyle: {
        color: '#666',
      },
    },
    series: [
      {
        name: '借阅次数',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: userNames.map((name, index) => ({
          name,
          value: borrowCounts[index],
        })),
        color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'],
        animationDuration: 1000,
        animationEasingUpdate: 'quinticInOut',
      },
    ],
  }

  userChart.setOption(option)
}

// 时间范围变化处理
const handleBookTimeRangeChange = (value) => {
  loading.value = true
  fetchHotBooks(value)
}

const handleUserTimeRangeChange = (value) => {
  loading.value = true
  fetchHotUsers(value)
}

// 页面加载时初始化
onMounted(() => {
  // 初始化图表实例
  initBookChart()
  initUserChart()

  // 获取数据
  fetchHotBooks()
  fetchHotUsers()

  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    if (bookChart) bookChart.resize()
    if (userChart) userChart.resize()
  })
})
</script>

<style scoped>
.statistics-dashboard {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background-color: #165dff;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  color: white;
  font-size: 18px;
  font-weight: 600;
  height: 100%;
  display: flex;
  align-items: center;
}

.menu {
  width: auto;
}

.content {
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.page-title {
  font-size: 26px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 24px;
  text-align: center;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.card {
  height: 100%;
  overflow: hidden;
  position: relative;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.card-title {
  color: #86909c;
  font-size: 14px;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 4px;
}

.card-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.trend-up {
  color: #00b42a;
  margin-right: 4px;
}

.trend-down {
  color: #f53f3f;
  margin-right: 4px;
}

.trend-desc {
  color: #86909c;
}

.charts-container {
  margin-bottom: 24px;
}

.chart-wrapper {
  transition: all 0.3s ease;
}

.chart-wrapper:hover {
  transform: translateY(-3px);
}

.chart-card {
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #1d2129;
}

.chart-content {
  height: 360px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.tables-container {
  margin-bottom: 24px;
}

.table-wrapper {
  transition: all 0.3s ease;
}

.table-wrapper:hover {
  transform: translateY(-3px);
}

.data-table {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.data-table:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.count-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e8f3ff;
  color: #165dff;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.footer {
  text-align: center;
  color: #86909c;
  border-top: 1px solid #f2f3f5;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .content {
    padding: 16px;
  }

  .page-title {
    font-size: 20px;
    margin-bottom: 16px;
  }

  .chart-content {
    height: 300px;
  }
}
</style>
